package com.erclab.xbuilder.formhelpers;

import java.util.HashMap;

import com.erclab.internal.xpresso.conf.Settings;
import com.erclab.internal.xpresso.datavalidators.DataValidationError;
import com.erclab.internal.xpresso.exceptions.FormException;
import com.erclab.internal.xpresso.exceptions.ObjectCreatorException;
import com.erclab.internal.xpresso.forms.Form;
import com.erclab.internal.xpresso.forms.FormHelper;
import com.erclab.internal.xpresso.util.FormElementUtil;
import com.erclab.internal.xpresso.util.ObjectCreator;
import com.erclab.xbuilder.db.MysqlDatabaseManager;
import com.erclab.xbuilder.exception.DBManagerException;

public class ObjectFormHelper implements FormHelper {

	public void afterFormCreation(Form theForm) throws FormException {
		// Nada to do

	}

	public void afterModification(Form theForm, HashMap keyValues) throws FormException, DataValidationError {
		// After the object has been inserted in the Objects table
		// we need to create the table to hold the objects
		String objectName = FormElementUtil.getElementValue(theForm, keyValues, "formName");
		if (theForm.getFormParameters().getAction().equals("insert")){
			String tableName = theForm.getFormParameters().getUser().getUserName() + "_" + objectName;
			createTable(tableName);
			createReport(objectName, tableName);
			createOptions(objectName);
		}
	}

	protected void createOptions(String objectName) {
		
	}
	
	protected void createReport(String objectName, String tableName) throws FormException  {
		ObjectCreator oc = Settings.getObjectCreator();
		try {
			oc.createReport(objectName, 
								tableName, 
								"SELECT * FROM " + tableName, 
								"Id" + tableName, 
								Integer.parseInt(Settings.getProperty("xbuilder_app_data.datasource")), 
								Integer.parseInt(Settings.getProperty("xbuilder_app_meta.datasource")));
		} catch (ObjectCreatorException e) {
			throw new FormException("An error occurred creating the report for the object: " + e);
		}
	}

	private void createTable(String tableName) throws FormException {
		MysqlDatabaseManager mdm = new MysqlDatabaseManager();
		try {
			mdm.createTable(tableName, null);
		} catch (DBManagerException e) {
			throw new FormException("An error occurred creating a table: " + e.getTheException());
		}
	}

	public void afterSubmission(Form theForm, HashMap keyValues)
			throws FormException, DataValidationError {
		// Nada to do

	}

	public void beforeFormCreation(Form theForm) throws FormException {
		// Nada to do

	}

}
